import tkinter as tk
from tkinter import ttk, messagebox
from GUI界面.BaseSubWindow import BaseSubWindow
from 数据库操作.FollowOperation import FollowOperation
from 数据库操作.CreateMysqlCon import CreateMysqlCon

class FansManage(BaseSubWindow):
    """
    粉丝管理
    """
    def create_widgets(self):
        # 创建标签页控件
        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建我的粉丝页面
        self.followers_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.followers_frame, text="我的粉丝")
        
        # 创建我的关注页面
        self.following_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.following_frame, text="我的关注")
        
        # 初始化粉丝页面
        self.init_followers_page()
        
        # 初始化关注页面
        self.init_following_page()
        
        # 绑定标签页切换事件
        self.notebook.bind("<<NotebookTabChanged>>", self.on_tab_changed)
    
    def init_followers_page(self):
        """初始化粉丝页面"""
        ttk.Label(self.followers_frame, text="我的粉丝", font=('Arial', 14)).pack(pady=10)
        
        # 创建带滚动条的树形视图框架
        tree_frame = ttk.Frame(self.followers_frame)
        tree_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(tree_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 创建树形视图
        self.followers_tree = ttk.Treeview(tree_frame, 
                                         columns=("id", "username", "follow_date"), 
                                         show="headings",
                                         yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.followers_tree.yview)
        
        # 配置列
        self.followers_tree.column("id", width=50)
        self.followers_tree.column("username", width=150)
        self.followers_tree.column("follow_date", width=150)
        
        # 设置列标题
        self.followers_tree.heading("id", text="ID")
        self.followers_tree.heading("username", text="用户名")
        self.followers_tree.heading("follow_date", text="关注时间")
        
        # 填充数据
        self.refresh_followers()
        
        self.followers_tree.pack(fill=tk.BOTH, expand=True)
        
        # 刷新按钮
        refresh_button = ttk.Button(self.followers_frame, text="刷新列表", command=self.refresh_followers)
        refresh_button.pack(pady=10)
    
    def init_following_page(self):
        """初始化关注页面"""
        ttk.Label(self.following_frame, text="我的关注", font=('Arial', 14)).pack(pady=10)
        
        # 创建带滚动条的树形视图框架
        tree_frame = ttk.Frame(self.following_frame)
        tree_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(tree_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 创建树形视图
        self.following_tree = ttk.Treeview(tree_frame, 
                                         columns=("id", "username", "follow_date"), 
                                         show="headings",
                                         yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.following_tree.yview)
        
        # 配置列
        self.following_tree.column("id", width=50)
        self.following_tree.column("username", width=150)
        self.following_tree.column("follow_date", width=150)
        
        # 设置列标题
        self.following_tree.heading("id", text="ID")
        self.following_tree.heading("username", text="用户名")
        self.following_tree.heading("follow_date", text="关注时间")
        
        # 填充数据
        self.refresh_following()
        
        self.following_tree.pack(fill=tk.BOTH, expand=True)
        
        # 绑定双击事件
        self.following_tree.bind("<Double-1>", self.unfollow_user)
        
        # 刷新按钮和取消关注按钮
        button_frame = ttk.Frame(self.following_frame)
        button_frame.pack(pady=10)
        
        refresh_button = ttk.Button(button_frame, text="刷新列表", command=self.refresh_following)
        refresh_button.pack(side=tk.LEFT, padx=5)
        
        unfollow_button = ttk.Button(button_frame, text="取消关注", command=lambda: self.unfollow_user(None))
        unfollow_button.pack(side=tk.LEFT, padx=5)
    
    def on_tab_changed(self, event):
        """标签页切换事件"""
        current_tab = self.notebook.index(self.notebook.select())
        if current_tab == 0:  # 粉丝页面
            self.refresh_followers()
        elif current_tab == 1:  # 关注页面
            self.refresh_following()
    
    def refresh_followers(self):
        """刷新粉丝列表"""
        # 清空现有数据
        for item in self.followers_tree.get_children():
            self.followers_tree.delete(item)
            
        try:
            # 获取用户ID
            cursor = CreateMysqlCon().get_con().cursor()
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
            user_id = cursor.fetchone()
            
            if user_id:
                # 获取并显示数据
                result = FollowOperation().get_followers(user_id[0])
                for row in result:
                    self.followers_tree.insert("", "end", values=row)
        except Exception as e:
            messagebox.showerror("错误", f"刷新粉丝列表失败: {e}")
            print(f"刷新粉丝列表失败: {e}")
    
    def refresh_following(self):
        """刷新关注列表"""
        # 清空现有数据
        for item in self.following_tree.get_children():
            self.following_tree.delete(item)
            
        try:
            # 获取用户ID
            cursor = CreateMysqlCon().get_con().cursor()
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
            user_id = cursor.fetchone()
            
            if user_id:
                # 获取并显示数据
                result = FollowOperation().get_following(user_id[0])
                for row in result:
                    self.following_tree.insert("", "end", values=row)
        except Exception as e:
            messagebox.showerror("错误", f"刷新关注列表失败: {e}")
            print(f"刷新关注列表失败: {e}")
    
    def unfollow_user(self, event):
        """取消关注用户"""
        try:
            # 获取选中项
            if event:  # 双击事件
                selected_items = [self.following_tree.selection()[0]]
            else:  # 按钮点击事件
                selected_items = self.following_tree.selection()
                
            if not selected_items:
                messagebox.showwarning("警告", "请先选择要取消关注的用户")
                return
            
            # 获取当前用户ID
            cursor = CreateMysqlCon().get_con().cursor()
            cursor.execute("SELECT ID FROM user_data WHERE username = %s", (self.user.username,))
            current_user_id = cursor.fetchone()[0]
            
            # 确认取消关注
            if not messagebox.askyesno("确认", "确定要取消关注选中的用户吗？"):
                return
            
            # 执行取消关注
            follow_op = FollowOperation()
            for item in selected_items:
                user_data = self.following_tree.item(item, "values")
                followed_id = user_data[0]
                followed_name = user_data[1]
                
                if follow_op.unfollow_user(current_user_id, followed_id):
                    self.following_tree.delete(item)
                    messagebox.showinfo("成功", f"已取消关注 {followed_name}")
                else:
                    messagebox.showerror("错误", f"取消关注 {followed_name} 失败")
            
            # 刷新关注列表
            self.refresh_following()
        except Exception as e:
            messagebox.showerror("错误", f"取消关注失败: {e}")
            print(f"取消关注失败: {e}")